package com.mask.roll.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mask.roll.common.code.ServiceEnums;
import com.mask.roll.common.constant.RollConstants;
import com.mask.roll.common.exception.RollException;
import com.mask.roll.edu.entity.Course;
import com.mask.roll.edu.entity.CourseDescription;
import com.mask.roll.edu.entity.VO.course.CourseFrontVo;
import com.mask.roll.edu.entity.VO.course.CourseInfoVo;
import com.mask.roll.edu.entity.VO.course.CoursePublishVo;
import com.mask.roll.edu.entity.VO.course.CourseWebVo;
import com.mask.roll.edu.mapper.CourseMapper;
import com.mask.roll.edu.service.ChapterService;
import com.mask.roll.edu.service.CourseDescriptionService;
import com.mask.roll.edu.service.CourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mask.roll.edu.service.VideoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author hx
 * @since 2021-10-23
 */
@Service
@Transactional
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Resource
    private CourseDescriptionService courseDescriptionService;

    @Resource
    private VideoService videoService;

    @Resource
    private ChapterService chapterService;

    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //向课程表中添加信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo,course);
        try {
            baseMapper.insert(course);
        } catch (Exception e) {
            log.error("添加课程失败:{}",e.getMessage());
            throw new RollException(ServiceEnums.COURSE_ADD_ERROR.getCode(),
                    RollConstants.ERROR,ServiceEnums.COURSE_ADD_ERROR.getMessage());
        }

        //获取添加课程后生成的随机id
        String courseId = course.getId();

        //向课程简介中添加信息
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(courseId);
        courseDescription.setDescription(courseInfoVo.getDescription());
        try {
            courseDescriptionService.save(courseDescription);
        }catch (Exception e) {
            log.error("添加课程简介失败:{}",e.getMessage());
            throw new RollException(ServiceEnums.COURSE_DESCRIPTION_ADD_ERROR.getCode(),
                    RollConstants.ERROR,ServiceEnums.COURSE_DESCRIPTION_ADD_ERROR.getMessage());
        }

        log.info("添加课程成功:{},课程id为{}",courseInfoVo,courseId);
        return courseId;
    }

    @Override
    public CourseInfoVo getInfoByCourseId(String courseId) {
        //查询课程信息
        Course course = new Course();
        try {
            course = baseMapper.selectById(courseId);
        } catch (Exception e) {
            log.info("查询课程信息失败:{}",e.getMessage());
            throw new RollException(ServiceEnums.COURSE_SELECT_INFO_FAILED.getCode(),
                    RollConstants.ERROR,ServiceEnums.COURSE_SELECT_INFO_FAILED.getMessage());
        }

        //查询课程描述信息
        CourseDescription courseDescription = new CourseDescription();
        try {
            courseDescription = courseDescriptionService.getById(courseId);
        } catch (Exception e) {
            log.error("查询课程简介信息失败:{}",e.getMessage());
            throw new RollException(ServiceEnums.COURSE_SELECT_DESCRIPTION_FAILED.getCode(),
                    RollConstants.ERROR,ServiceEnums.COURSE_SELECT_DESCRIPTION_FAILED.getMessage());
        }
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(course,courseInfoVo);
        courseInfoVo.setDescription(courseDescription.getDescription());

        log.info("课程id:{}查询课程信息成功:{}",courseId,courseInfoVo);
        return courseInfoVo;
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {

        //修改课程信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo,course);
        try {
            baseMapper.updateById(course);
        }catch (Exception e){
            log.error("修改课程信息失败:{}",e.getMessage());
            throw new RollException(ServiceEnums.COURSE_INFO_UPDATE_FAILED.getCode(),
                    RollConstants.ERROR,ServiceEnums.COURSE_INFO_UPDATE_FAILED.getMessage());
        }

        //修改描述信息
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(courseInfoVo.getId());
        courseDescription.setDescription(courseInfoVo.getDescription());
        try {
            courseDescriptionService.updateById(courseDescription);
            log.info("修改课程信息成功:{}",courseInfoVo);
        } catch (Exception e) {
            log.info("修改课程描述信息失败:{}",e.getMessage());
            throw new RollException(ServiceEnums.COURSE_DESCRIPTION_UPDATE_FAILED.getCode(),
                    RollConstants.ERROR,ServiceEnums.COURSE_DESCRIPTION_UPDATE_FAILED.getMessage());
        }

    }

    @Override
    public CoursePublishVo publishCourseInfo(String id) {
        return baseMapper.getPublishCourseInfo(id);
    }

    @Override
    public void removeCourse(String courseId) {
        //删除小节
        videoService.removeVideoByCourseId(courseId);

        //删除章节
        chapterService.removeChapterByCourseId(courseId);

        //删除描述
        courseDescriptionService.removeById(courseId);

        //删除课程
        try {
            baseMapper.deleteById(courseId);
            log.info("删除课程{}成功",courseId);
        } catch (Exception e) {
            log.error("删除课程{}失败:{}",courseId,e.getMessage());
            throw new RollException(ServiceEnums.COURSE_DELETE_FAILED.getCode(),
                    RollConstants.ERROR,ServiceEnums.COURSE_DELETE_FAILED.getMessage());
        }

    }

    /**
     * 条件查询带分页查询课程
     * @param pageParam
     * @param courseFrontVo
     * @return
     */
    @Override
    public Map<String, Object> getCourseFrontList(Page<Course> pageParam, CourseFrontVo courseFrontVo) {
        //2 根据讲师id查询所讲课程
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) { //一级分类
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectId())) { //二级分类
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) { //关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) { //最新
            wrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {//价格
            wrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam,wrapper);

        List<Course> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();//下一页
        boolean hasPrevious = pageParam.hasPrevious();//上一页

        //把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        //map返回
        return map;
    }

    /**
     * 根据课程id，编写sql语句查询课程信息
     * @param courseId
     * @return
     */
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }
}
